import React, {Component} from "react";
import {
    Space, Button, Table, Row, Col, Input, Modal,
    Breadcrumb, PageHeader, Form, TreeSelect, message
} from "antd";

import {
    SearchOutlined, DeleteOutlined
    , EditOutlined
} from "@ant-design/icons";

import axios from "@src/lib/axios";
import "@src/style/tableCom.scss";
import "@src/style/common.scss";

export default class SearchCityConf extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading:true,
            value: "",
            treeData: [ //适合异步加载数据需要的格式
                // {id: 1, pId: 0, value: '1', title: 'Expand to load'},
                // {id: 2, pId: 0, value: '2', title: 'Expand to load'},
                // {id: 3, pId: 0, value: '3', title: 'Tree Node', isLeaf: true},
            ],
            allTreeData:[],
            modal_title: "",
            formRef: React.createRef(),
            form: React.createRef(),
            params: {
                name: "",
                first_lash: "",
                limit: 15,
                page: 1,
            },

            list: [],
            visible: false,
            confirmLoading: false,
            initValuesModa: {
                id:"",
                area_id: "",
                pinyin: "",
                first_lash: ""
            },
            option:"",
        };
        this.fetchData()
        this.getAllProvince(7);
        this.getAllTreeData();

    }

    getAllTreeData = ()=>{
        axios.post('/common/get_tree_data').then(res => {
            this.setState({allTreeData:res.data})
        });
    }

    //获取所有中国一级地区
    getAllProvince = (id) => {
        axios.post('/common/sync_get_area').then(res => {
            if (res.code == 0) {
                let {data} = res
                this.setState({
                    treeData: data
                })
            }
        })
    }


    //列表查询
    fetchData = () => {
        this.setState({loading:true})
        const {params, list} = this.state;
        axios.post("/platform/search_conf", params).then(res => {
            if (res.code === 0) {
                let data = res.data;
                this.setState({
                    list: data,
                    loading:false
                });
            }
        });
    }

    //完成
    onSearch = (values) => {
        console.log(values);
        Object.assign(this.state.params, values)
        this.fetchData();
    }
    //查询下级地区
    onChange = (value) => {
        console.log(value);
        this.setState({value});
    }
    onValuesChange = (changedValues, allValues) => {
        console.log(changedValues, allValues);
        Object.assign(this.state.params, {...changedValues});
        this.fetchData();
    };
    showModal = (title) => {
        let url = "/platform/search_conf/update";
        if (title === '添加配置') {
            this.setState({initValuesModa:{id:""}});
            url = "/platform/search_conf/add";
        }
        this.setState({visible: true, confirmLoading: false, modal_title: title,option_url:url});
    }

    handleEdit = (record) =>{
        console.log(record);
        this.showModal("编辑配置");
        let {id,first_lash,pinyin,area_path} = record
        this.setState({initValuesModa:{id:id,area_id:area_path,pinyin:pinyin,first_lash:first_lash}})
    }



    handleOk = () => {
        this.state.form.current.validateFields().then(values => {
            this.setState({confirmLoading: true})
            let postData = this.state.form.current.getFieldsValue();
            Object.assign(this.state.initValuesModa,postData);
            //保存
            axios.post(this.state.option_url, this.state.initValuesModa).then(res => {
                if (res.code === 0) {
                    this.state.form.current.resetFields();
                    this.setState({confirmLoading: false, visible: false});
                    this.fetchData()
                } else {
                    message.warning(res.msg);
                    this.setState({confirmLoading: false})
                }
            }).catch(res => {
                this.setState({confirmLoading: false})
            });

        }).catch(err => {

        });
    };
    handleCancel = () => {
        console.log("cancel");
        this.setState({initValuesModa:{area_id:"",pinyin:"",first_lash:""}})
        this.setState({visible: false, confirmLoading: false})
    }



    /**
     * 删除
     */
    handleDelete = (id) => {
        axios.post('/platform/search_conf/del', {id}).then(res => {
            if (res.code === 0) {
                this.fetchData();
            } else {
                message.warn(res.msg);
                this.fetchData();
            }
        }).catch(err => {

        })
    }




    render() {
        let {params, list, visible, confirmLoading, treeData, value, initValuesModa,loading} = this.state;
        const style = {padding: '8px 0'};
        const layout = {
            labelCol: {span: 8},
            wrapperCol: {span: 16},
        };


        const layoutAdd = {
            labelCol: {span: 4},
            wrapperCol: {span: 24},
        };

        const columns = [
            {title: "城市名称", dataIndex: "name", align: "center"},
            {title: "拼音首字母", dataIndex: "first_lash", align: "center"},
            {title: "拼音", dataIndex: "pinyin", align: "center"},
            {title: "地区id", dataIndex: "area_id", align: "center"},
            {title: "操作", dataIndex: "id", align: "center", render: (id, record) => {
                    return (
                        <Space size={"middle"}>
                            <Button size="small" type="danger" onClick={()=>this.handleDelete(record.id)}><DeleteOutlined/>删除</Button>
                            <Button size="small" type="primary" onClick={()=>this.handleEdit(record)}><EditOutlined/>修改</Button>
                        </Space>
                    )
                }
            }
        ]


        return (
            <div style={{padding: "0 15px 100px 15px", background: "#fff"}}>
                <div style={{padding: "10px 0px 1px 0px"}}>
                    <Breadcrumb>
                        <Breadcrumb.Item>配置管理</Breadcrumb.Item>
                        <Breadcrumb.Item>
                            <a href="">热门城市</a>
                        </Breadcrumb.Item>
                    </Breadcrumb>
                </div>
                <PageHeader
                    className="site-page-header"
                    title="热门城市配置"
                    subTitle="配置前端搜索栏目城市"
                />
                <Form
                    rel={this.state.formRef}
                    {...layout}
                    name="basic"
                    onFinish={this.onSearch}
                    onValuesChange={this.onValuesChange}
                >

                    <Row gutter={16} style={{marginBottom: "10px"}}>
                        <Col className="gutter-row" span={5}>
                            <Form.Item
                                name={"name"}
                                label={"城市名称"}
                            >
                                <Input placeholder="城市名称" allowClear/>
                            </Form.Item>
                        </Col>
                        <Col className="gutter-row" span={4}>
                            <Form.Item
                                name={"first_lash"}
                                label={"首字母"}
                            >
                                <Input placeholder="城市拼音首字母" allowClear/>
                            </Form.Item>
                        </Col>
                        <Col className="gutter-row">
                            <Button type="primary" htmlType="submit"><SearchOutlined/>查询</Button>
                        </Col>
                    </Row>
                </Form>

                <Button
                    onClick={()=>this.showModal("添加配置")}
                    type="primary"
                    style={{
                        marginBottom: 16,
                    }}
                >
                    添加城市
                </Button>

                <Modal
                    title={this.state.modal_title}
                    visible={visible}
                    onOk={this.handleOk}
                    confirmLoading={confirmLoading}
                    onCancel={this.handleCancel}
                    destroyOnClose={true}
                >
                    <Form
                        {...layoutAdd}
                        ref={this.state.form}
                        name="add_save"
                        initialValues={initValuesModa}
                    >
                        <Form.Item
                            label="所属行政地区"
                            name="area_id"
                            labelCol={{span: 6}}
                            rules={[{required: true, message: '所属行政地区未填写！'}]}
                        >
                            <TreeSelect
                                style={{ width: '100%' }}
                                value={this.state.value}
                                dropdownStyle={{ maxHeight: 400, maxWidth:1200 ,overflow: 'auto' }}
                                treeData={this.state.allTreeData}
                                placeholder="请选择城市"
                                treeDefaultExpandAll={false}
                                onChange={this.onChange}
                            />
                        </Form.Item>


                        <Form.Item
                            label="城市拼音"
                            labelCol={{span: 6}}
                            name="pinyin"
                            rules={[{required: true, message: '城市拼音未填写！'}]}
                        >
                            <Input placeholder="输入城市拼音"/>
                        </Form.Item>

                        <Form.Item
                            label="拼音首字母"
                            name="first_lash"
                            labelCol={{span: 6}}
                            rules={[{required: true, message: '拼音首字母未填写！'}]}
                        >
                            <Input placeholder="输入拼音首字母"/>
                        </Form.Item>
                    </Form>
                </Modal>
                <Table
                    loading={loading}
                    size="small"
                    columns={columns}
                    rowKey="id"
                    dataSource={list}
                    pagination={true}
                />
            </div>
        )
    }


}